package ink.metoo.auto.fishpi.job

import ink.metoo.auto.fishpi.ClientCaches
import ink.metoo.auto.fishpi.Log
import ink.metoo.auto.fishpi.Settings
import ink.metoo.auto.fishpi.call.ArticleCall
import ink.metoo.auto.fishpi.call.CommentCall

class AutoCommentArticleJob : RunnableJob {

    private val maxCommentCount = 5

    override fun run() {
        var p = 1
        val maxP = 10
        // 重试次数 预防无限循环
        var retryCount = 3
        val frc = retryCount
        while (ClientCaches.everydayState.commentCount < maxCommentCount && retryCount > 0 && p <= maxP) {
            try {
                ArticleCall.getArticles(p = p, size = 20).data?.let { data ->
                    // maxP = data.pagination.paginationPageCount
                    data.articles.forEach { at ->
                        // 休息30秒
                        Thread.sleep(1000 * 60)
                        tryComment(at.oId)
                        if (ClientCaches.everydayState.commentCount >= maxCommentCount) {
                            return
                        }
                    }
                }
                retryCount = frc
            } catch (e: Exception) {
                retryCount--
                Log.error("评论文章发生错误 retry: ${frc - retryCount}", e)
            }
            p++
        }
    }

    companion object {

        fun tryComment(oid: String) {
            ArticleCall.getArticle(oid).data?.article?.let { ad ->
                // 文章是否启用评论
                if (!ad["articleCommentable"].asBoolean) {
                    return
                }
                // 是否是我的文章
                if (ad["isMyArticle"].asBoolean) {
                    return
                }
                // 文章状态， 0 = 正常，1 = 封禁，2 = 锁定
                if (ad["articleStatus"].asInt != 0) {
                    return
                }
                val articleCommentsJsonArray = ad["articleComments"].asJsonArray
                var myComment = articleCommentsJsonArray.find { comment ->
                    comment.asJsonObject["commentAuthorName"].asString == Settings.fishpiClient.username
                }
                val articleCommentCount = ad["articleCommentCount"].asInt
                var loadCommentCount = articleCommentsJsonArray.size()
                var p = 2
                while (articleCommentCount != loadCommentCount && p != 10) {
                    if (myComment != null) {
                        return@let
                    }
                    val articleComments =
                        CommentCall.articleComments(oid, p)["data"].asJsonObject["articleComments"].asJsonArray
                    loadCommentCount += articleComments.size()
                    myComment = articleComments.find { comment ->
                        comment.asJsonObject["commentAuthorName"].asString == Settings.fishpiClient.username
                    }
                    p++
                }

                // 检测是否评论过
                if (myComment != null) {
                    return@let
                }
                val commentText = Settings.community.commentTexts.random()
                val commentResult = CommentCall.comment(oid, commentText)

                if (commentResult.code == 0) {
                    ClientCaches.refreshEverydayState {
                        it.commentCount++
                    }
                    Log.info("article comment $commentText success $oid ${ad["articleTitleEmoj"]} ")
                } else {
                    Log.error("article comment fail $oid ${ad["articleTitleEmoj"]} errMessage: ${commentResult.msg}")
                }
            }
        }

    }

}